<template>
  <div>
    <el-dialog
        title="设置服务统计"
        v-el-drag-dialog
        :visible="config.show===true"
        :close-on-click-modal="false"
        :before-close="handleClose"
    >
      <el-container style="height:500px">
        <el-aside width="260px" style="padding: 0px; margin-bottom: 0px;" >
          <el-header>字段集</el-header>
          <el-menu style="height: 470px; overflow: auto;border: 1px solid #ddd; border-radius: 4px;">
            <el-menu-item
                v-for="field in configData.fieldData"
                @click="handleSelectFieldMenu(field.f_field)"
                :class="{'selected':currentField==field.f_field}"
            >
              <span type="fieldcn">{{ field.f_field }}</span>
              <span type="field"
                    style="border-radius: 3px; background-color:teal; color: #fff; margin-left: 3px; padding: 2px 3px;">{{
                  field.f_fieldcn
                }}</span>
              <i class="el-icon-check"
                 v-if="configData.fieldValues.hasOwnProperty(field.f_field)?(configData.fieldValues[field.f_field].isStatistics!=0?true:false):false"></i>
            </el-menu-item>
          </el-menu>
        </el-aside>
        <el-container>
          <el-header>当前编辑字段：{{ currentField }}</el-header>
          <el-main>
            <el-form ref="form" label-width="120px">
              <el-row>
                <el-col :span="10">
                  <el-form-item label="是否统计字段：">
                    <el-switch size="mini" v-model="currentFieldIsStatisticsField"></el-switch>
                  </el-form-item>
                </el-col>
                <el-col :span="1">&ensp;</el-col>
                <el-col :span="2">
                  <el-button type="primary" size="mini" icon="el-icon-delete" @click="deleteCurrentFieldConfig">
                    清除当前字段配置
                  </el-button>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="合并字段：">
                    <el-select size="mini" style="width: 100%;" value-key="value" v-model="currentFieldData.mergeFields"
                               filterable>
                      <el-option v-for="field in configData.fieldData"
                                 :key="field.f_field"
                                 :label="field.f_fieldcn"
                                 :value="field.f_field"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="统计值字段：">
                    <el-select size="mini" style="width: 100%;" value-key="value"
                               v-model="currentFieldData.statisticValueField" filterable>
                      <el-option v-for="field in statisticsValueField"
                                 :key="field.f_field"
                                 :label="field.f_fieldcn"
                                 :value="field.f_field"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-divider content-position="left">字段枚举值</el-divider>
              <el-row>
                <el-button type="primary" size="mini" icon="el-icon-plus"
                           @click="fieldValueOperate('addRootFieldValue',-1,null)">添加根值
                </el-button>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-table
                      ref="fieldsTable"
                      :data="currentFieldData.fieldValues"
                      height="300"
                      style="width: 100%;"
                      row-key="id"
                      border
                      :tree-props="{children:'children',hasChildren:'hasChildren'}"
                  >
                    <el-table-column
                        prop="title"
                        label="标题"
                        align="left"
                        width="200"
                    ></el-table-column>
                    <el-table-column
                        prop="value"
                        label="值"
                        align="left"
                    ></el-table-column>
                    <el-table-column
                        label="操作"
                        align="center"
                        width="200"
                    >
                      <template slot-scope="scope">
                        <el-button type="text" size="mini" icon="el-icon-plus"
                                   @click="fieldValueOperate('addSubFieldValue',scope.$index,scope.row)">添加
                        </el-button>
                        <el-button type="text" size="mini" icon="el-icon-edit"
                                   @click="fieldValueOperate('editFieldValue',scope.$index,scope.row)">编辑
                        </el-button>
                        <el-button type="text" size="mini" icon="el-icon-delete"
                                   @click="fieldValueOperate('deleteFieldValue',scope.$index,scope.row)">删除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-dialog
                      width="30%"
                      :title="fieldValueSubDialog.dialogTitle"
                      :visible.sync="fieldValueSubDialog.visible"
                      append-to-body
                  >
                    <el-form-item style="margin-bottom: 10px;" label="标题：">
                      <el-input v-model="fieldValueSubDialog.title"></el-input>
                    </el-form-item>
                    <el-form-item label="值：">
                      <el-input v-model="fieldValueSubDialog.value"></el-input>
                    </el-form-item>
                    <span slot="footer" class="dialog-footer">
                      <el-button type="primary" @click="handleOkSub">确定</el-button>
                      <el-button @click="handleCloseSub">取消</el-button>
                    </span>
                  </el-dialog>
                </el-col>
              </el-row>
            </el-form>
          </el-main>
        </el-container>
      </el-container>
      <span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="handleOk">确定</el-button>
				<el-button @click="handleClose">取消</el-button>
			</span>
    </el-dialog>
  </div>
</template>

<script>
import {IsNotNullStr, extend, formatInsertToArrayByPid} from "@/utils/Global/GlobalCommonFunction";
import { updateCatalogStatistics, queryCatalogStatistics, queryCatalogQuery } from '@/api/resource/resourceCatalog'
import elDragDialog from '@/directive/el-dragDialog/'

export default {
  name: "editServiceStatistics",
  data() {
    return {
      selectedMergeField: null,
      selectedStatisticValueField: null,
      currentField: "",
      currentFieldData: {
        isStatistics: 0,//是否统计字段
        mergeFields: [],//统计字段
        statisticValueField: "",//统计值字段
        fieldValues: []//统计字段值域
      },
      configData: {
        serviceStatisticsData: null,
        fieldValues: {},
        fieldData: []
      },
      fieldValueSubDialog: {
        rowid:"",
        type: "",
        dialogTitle: "",
        visible: false,
        pid: "",
        value: "",
        title: ""
      }
    }
  },
  props: {
    config: {
      type: Object,
      default() {
        return {
          show: false,
        }
      }
    },
    param: {
      type: Object,
      default() {
        return {}
      }
    },
    form: {
      type: Object,
      default() {
        return {
          serviceId: "",
        }
      }
    },
  },
  computed: {
    currentFieldIsStatisticsField: {
      get() {
        return this.currentFieldData.isStatistics == 0 ? false : true;
      },
      set(value) {
        this.currentFieldData.isStatistics = value ? 1 : 0;
      }
    },
    statisticsValueField() {
      return extend([], this.configData.fieldData, [
        {"f_fieldcn": "几何面积", "f_field": "#area"},
        {"f_fieldcn": "几何长度", "f_field": "#length"}
      ]);
    }
  },
  directives: {//到这里了，看看自定义组件怎么个用法
    elDragDialog,
  },
  mounted() {
    this.queryServiceQueryData(this.form.serviceId);
    this.queryServiceStatisticsData(this.form.serviceId);
  },
  methods: {
    deleteCurrentFieldConfig() {
      let that = this;
      if (that.configData.fieldValues.hasOwnProperty(that.currentField)) {
        delete that.configData.fieldValues[that.currentField];
      }
      that.initFieldStatistics(that.currentField);
    },
    /**
     * 根据值删除字段值
     * @param value
     * @param fieldValues
     */
    deleteFieldValueByValue(value, fieldValues) {
      let that = this;
      for (let i in fieldValues) {
        let item = fieldValues[i];
        if (value == item.value) {
          fieldValues.splice(i, 1);
        } else {
          that.deleteFieldValueByValue(value, item.children);
        }
      }
    },
    /**
     * 字段操作
     * @param operateType 操作类型
     * @param index
     * @param row
     */
    fieldValueOperate(operateType, index, row) {
      let that = this;
      if (IsNotNullStr(that.currentField)) {
        that.fieldValueSubDialog.type = operateType;
        switch (operateType) {
          case "addRootFieldValue"://添加字段值根值
            that.fieldValueSubDialog.visible = true;
            that.fieldValueSubDialog.pid = "";
            that.fieldValueSubDialog.dialogTitle = "添加根值";
            that.fieldValueSubDialog.title = "";
            that.fieldValueSubDialog.value = "";
            that.fieldValueSubDialog.rowid="";
            break;
          case "addSubFieldValue"://添加字段值节点
            that.fieldValueSubDialog.visible = true;
            that.fieldValueSubDialog.pid = row.id;
            that.fieldValueSubDialog.dialogTitle = "添加(" + row.title + ")的子字段值";
            that.fieldValueSubDialog.title = "";
            that.fieldValueSubDialog.value = "";
            that.fieldValueSubDialog.rowid="";
            break;
          case "editFieldValue"://编辑字段值
            that.fieldValueSubDialog.visible = true;
            that.fieldValueSubDialog.pid = row.pid;
            that.fieldValueSubDialog.dialogTitle = "编辑字段值";
            that.fieldValueSubDialog.title = row.title;
            that.fieldValueSubDialog.value = row.value;
            that.fieldValueSubDialog.rowid=row.id;
            break;
          case "deleteFieldValue"://删除字段值
            this.$confirm("删除字段值（" + row.title + "：" + row.value + "）？", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(() => {
              that.deleteFieldValueByValue(row.value, that.currentFieldData.fieldValues);
              this.$message({
                type: "success",
                message: "删除成功！"
              });
            }).catch(() => {
            });
            break;
        }
      } else {
        this.$message({
          message: "请选择统计字段！",
          type: "warning"
        });
      }
    },
    //格式化统计字段值域，数据库保存为id、pid，当前代码更改为children方式
    formatFieldValuePidToChildren(fieldValues) {
      let result = [];
      //遍历fieldValues
      for (let i in fieldValues) {
        let fieldValue = fieldValues[i];
        formatInsertToArrayByPid(result, fieldValue, "id", "pid");
      }
      return result;
    },
    formatCurrentFieldValueChildrenToPid(fieldValues, pid) {
      let that = this;
      let result = [];
      for (let i in fieldValues) {
        let fieldValue = fieldValues[i];
        let obj1 = {};
        if (pid != null && pid != "") {
          obj1 = {pid: pid};
        }
        let fieldValue1 = extend({}, obj1, fieldValue);
        delete fieldValue1.children;
        result.push(fieldValue1);
        if (fieldValue.children.length > 0) {
          let result1 = that.formatCurrentFieldValueChildrenToPid(fieldValue.children, fieldValue.id);
          result = result.concat(result1);
        }
      }
      return result;
    },

    /**
     * 关闭弹窗
     */
    handleClose() {
      let that = this;
      that.config.show = false;
    },
    handleOk() {
      let that = this;
      //保存当前字段配置至configData
      if (that.configData.fieldValues.hasOwnProperty(that.currentField)) {
        that.configData.fieldValues[that.currentField] = extend({}, {}, that.currentFieldData);
        that.configData.fieldValues[that.currentField].fieldValues = that.formatCurrentFieldValueChildrenToPid(that.currentFieldData.fieldValues, "");
      }
      let param = {
        serviceId: that.form.serviceId,
        fieldConfig: JSON.stringify(that.configData.fieldValues)
      };
      updateCatalogStatistics(param).then((res) => {
        if (res.code == "200") {
          this.$message({
            type: "success",
            message: "保存！"
          });
          that.config.show = false;
        } else {
          this.$message.error("保存失败！");
        }
      }).catch(resp => {
        console.log('queryCatalogQuery', resp.status + "," + resp.statusText);
      });
    },
    handleCloseSub() {
      let that = this;
      that.fieldValueSubDialog.visible = false;
    },
    handleOkSub() {
      let that = this;
      let fieldValueObj = extend({}, {children: []}, {
        id: that.fieldValueSubDialog.value,
        pid: that.fieldValueSubDialog.pid,
        title: that.fieldValueSubDialog.title,
        value: that.fieldValueSubDialog.value
      });
      switch (that.fieldValueSubDialog.type) {
        case "addRootFieldValue"://添加字段值根值
          if (!that.isRepeatFieldValue(fieldValueObj, that.currentFieldData.fieldValues)) {
            that.currentFieldData.fieldValues.push(fieldValueObj);
            that.fieldValueSubDialog.visible = false;
          } else {
            this.$message({
              message: "字段或标题值重复！",
              type: "warning"
            });
          }
          break;
        case "addSubFieldValue"://添加字段值节点
          if (IsNotNullStr(fieldValueObj.title) && IsNotNullStr(fieldValueObj.value)) {
            if (!that.isRepeatFieldValue(fieldValueObj, that.currentFieldData.fieldValues)) {
              that.addSubFieldValue(fieldValueObj, that.currentFieldData.fieldValues);
              that.fieldValueSubDialog.visible = false;
            } else {
              this.$message({
                message: "字段或标题值重复！",
                type: "warning"
              });
            }
          } else {
            this.$message({
              message: "字段或标题值为空！",
              type: "warning"
            });
          }
          break;
        case "editFieldValue"://编辑字段值
          if (IsNotNullStr(fieldValueObj.title) && IsNotNullStr(fieldValueObj.value)) {
              that.editSubFieldValue(fieldValueObj, that.currentFieldData.fieldValues, that.fieldValueSubDialog.rowid);
              that.fieldValueSubDialog.visible = false;
          } else {
            this.$message({
              message: "字段或标题值为空！",
              type: "warning"
            });
          }
          break;
      }
    },
    /**
     * 添加字段值
     * @param fieldValueObj
     * @param fieldValues
     * @returns {boolean} 是否添加成功
     */
    addSubFieldValue(fieldValueObj, fieldValues) {
      let that = this;
      let result = false;
      for (let i in fieldValues) {
        if (fieldValueObj.pid == fieldValues[i].id) {
          fieldValues[i].children.push(fieldValueObj);
          result = true;
          break;
        } else {
          result = that.addSubFieldValue(fieldValueObj, fieldValues[i].children);
          if (result) {
            break;
          }
        }
      }
      return result;
    },
    /**
     * 编辑字段值
     * @param fieldValueObj
     * @param fieldValues
     * @param editId
     * @returns {boolean} 是否添加成功
     */
    editSubFieldValue(fieldValueObj, fieldValues, editId) {
      let that = this;
      let result = false;
      for (let i in fieldValues) {
        if (editId == fieldValues[i].id) {
          fieldValues[i].id = fieldValueObj.id;
          fieldValues[i].title = fieldValueObj.title;
          fieldValues[i].value = fieldValueObj.value;
          result = true;
          break;
        } else {
          result = that.addSubFieldValue(fieldValueObj, fieldValues[i].children);
          if (result) {
            break;
          }
        }
      }
      return result;
    },
    /**
     * 查询字段值是否重复，标题或者值重复
     * @param fieldValueObj
     * @param fieldValues
     * @returns {boolean}
     */
    isRepeatFieldValue(fieldValueObj, fieldValues) {
      let that = this;
      let result = false;
      for (let i in fieldValues) {
        if (fieldValueObj.title == fieldValues[i].title || fieldValueObj.value == fieldValues[i].value) {
          result = true;
          break;
        } else {
          result = that.isRepeatFieldValue(fieldValueObj, fieldValues[i].children);
          if (result) {
            break;
          }
        }
      }
      return result;
    },
    /**
     * 查询数据服务配置
     * @serviceId serviceId
     */
    queryServiceQueryData(serviceId) {
      let that = this;
      queryCatalogQuery(serviceId).then((res) => {
        if (res.data.queryData.length > 0) {
          let obj = res.data.queryData[0];
          that.configData.fieldData = JSON.parse(obj.fieldConfig);
        }
      }).catch(resp => {
        console.log('queryCatalogQuery', resp.status + "," + resp.statusText);
      });

    },
    /**
     * 服务统计查询
     * @serviceId serviceId
     */
    queryServiceStatisticsData(serviceId) {
      let that = this;
      queryCatalogStatistics(serviceId).then((res) => {
        if (res.data.statisticsData.length > 0) {
          let obj = res.data.statisticsData[0];
          that.configData.fieldValues = JSON.parse(obj.fieldConfig);
        }
      }).catch(resp => {
        console.log('queryCatalogQuery', resp.status + "," + resp.statusText);
      });

    },
    /**
     * 点击左侧字段按钮事件
     * @param field
     */
    handleSelectFieldMenu(field) {
      let that = this;
      if (that.configData.fieldValues.hasOwnProperty(that.currentField)) {
        that.configData.fieldValues[that.currentField] = extend({}, {}, that.currentFieldData);
        that.configData.fieldValues[that.currentField].fieldValues = that.formatCurrentFieldValueChildrenToPid(that.currentFieldData.fieldValues, "");
      }
      that.currentField = field;
      that.initFieldStatistics(that.currentField);
    },
    /**
     * 根据字段初始化该字段的统计配置
     * @param field
     */
    initFieldStatistics(field) {
      let that = this;
      //初始化统计配置
      let fieldItem = {
        "isStatistics": 0,
        "mergeFields": [],
        "statisticValueField": "",
        "fieldValues": []
      };
      if (that.configData.fieldValues.hasOwnProperty(field)) {
        fieldItem = that.configData.fieldValues[field];
      } else {
        //字段值未存储，需要初始化
        that.configData.fieldValues[field] = fieldItem;
      }
      that.currentFieldData = fieldItem;
      that.currentFieldData.fieldValues = extend([], [], that.formatFieldValuePidToChildren(that.currentFieldData.fieldValues));
    }
  }
}
</script>

<style scoped>
::v-deep .selected {
  background-color: #b9d2e3;
}

::v-deep .el-header {
  height: 30px !important;
}

::v-deep .el-main {
  padding: 0px 20px;
}

::v-deep .el-menu-item {
  height: 40px;
  line-height: 40px;
}

::v-deep .el-form-item {
  margin-bottom: 0px;
}

::v-deep .el-divider--horizontal {
  margin: 15px 0px;
}

::v-deep .el-form-item__label {
  line-height: 30px;
}

::v-deep .el-form-item__content {
  line-height: 30px;
}
</style>
